package com.hzhc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.aliyun.RecognizePdf;
import com.hzhc.entity.*;
import com.hzhc.enumBean.DdEnum;
import com.hzhc.enumBean.FyEnum;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.enumBean.YwOrderTypeEnum;
import com.hzhc.mapper.*;
import com.hzhc.service.*;
import com.hzhc.utils.ResultUtil;
import com.hzhc.utils.StringUtils;
import com.hzhc.vo.*;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务委托 服务实现类
 * </p>
 *
 * @author Fchenxu
 * @since 2024-05-27
 */
@Service
@RequiredArgsConstructor
public class YwOrderServiceImpl extends ServiceImpl<YwOrderMapper, YwOrder> implements YwOrderService {

    private final TbSequenceService tbSequenceService;
    private final YwOrderCntrService ywOrderCntrService;
    private final YwOrderCntrMapper cntrMapper;
    private final YwOrderCarMapper carMapper;
    private final VehicleReservationMapper vehicleReservationMapper;
    private final VehicleReservationService vehicleReservationService;
    private final YwOrderCarMapper ywOrderCarMapper;
    private final YwOrderCarService ywOrderCarService;
    private final SysUserMapper userMapper;
    private final CntrImgFileMapper cntrImgFileMapper;
    private final YwOrderFileMapper ywOrderFileMapper;
    private final CompanyInfoMapper companyInfoMapper;
    private final CntrInfoService cntrInfoService;
    private final CntrLogService cntrLogService;
    private final CntrInfoMapper cntrInfoMapper;
    private final YwOrderShipService ywOrderShipService;
    private final SysMsgNotifyService notifyService;
    private final YwOrderCntrMapper ywOrderCntrMapper;
    private final SysAuthMapper authMapper;
    private final DeclareCarMapper declareCarMapper;

    @Override
    public List<YwOrderVo> getOrderPage(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> orderPage = baseMapper.getOrder(page, vo);
        for (YwOrderVo record : orderPage.getRecords()) {
            if(StringUtils.isNotEmpty(record.getCntrMsg())){
                JSONArray array=JSONArray.parseArray(record.getCntrMsg());
                if(!array.isEmpty()){
                    JSONObject o =(JSONObject) array.get(0);
                    record.setCntrListNum((Integer) o.get("cntrCount"));
                }
            }
        }
        return orderPage.getRecords();
    }

    @Override
    public ResultUtil<T> addOrder(YwOrderVo vo,String url) {
        if(vo.getFinishFlag()!=null && vo.getFinishFlag()==1 && vo.getCntrList().isEmpty()){
            if(vo.getCntrQdList()==null){
                return ResultUtil.build(ResultUtilCodeEnum.YWORDER_NO_CNTR);
            }
        }
        if(vo.getFinishFlag()==null){
            vo.setFinishFlag(0);
        }
        YwOrder order = new YwOrder();
        order.setOrderType(vo.getOrderType());
        order.setCompanyId(vo.getCompanyId());
        order.setCompanyName(vo.getCompanyName());
        order.setWorkTime(vo.getWorkTime());
        order.setOrderState(vo.getOrderState());
        order.setCreateTime(vo.getCreateTime());
        order.setUserId(vo.getUserId()==null?vo.getMemberId():vo.getUserId());
        order.setUserName(vo.getUserName());
        order.setTkWorkState(vo.getTkWorkState());
        order.setAccessPath(vo.getAccessPath());
        if(vo.getFinishFlag()!=null){
            order.setFinishFlag(vo.getFinishFlag());
        }
        if(vo.getEfcomState()!=null){
            order.setEfcomState(vo.getEfcomState());
        }
        String orderNo="";
        if("ZJ".equals(vo.getOrderType())){
            orderNo  = "ZJ" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        }else if ("TK".equals(vo.getOrderType())){
            orderNo  = "TK" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        }else if ("TZ".equals(vo.getOrderType())){
            orderNo  = "TZ" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        }else if ("KJ".equals(vo.getOrderType())){
            orderNo  = "KJ" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        }else if ("SGJ".equals(vo.getOrderType())){
            orderNo  = "SGJ" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        }else if ("HK".equals(vo.getOrderType())){
            orderNo  = "HK" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        } else if (YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
            orderNo  = YwOrderTypeEnum.TZHK.getCode() + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        }
        order.setOrderNo(orderNo);

        if (("TK".equals(vo.getOrderType()) || "KJ".equals(vo.getOrderType()) || "HK".equals(vo.getOrderType()))  && (vo.getTkWorkState()!=null && vo.getTkWorkState()==1) ){
            JSONArray array = new JSONArray();
            if (!vo.getCntrQdList().isEmpty()){
                List<CntrQdVo> voList = vo.getCntrQdList();
                for (CntrQdVo qd : voList) {
                    JSONObject json=new JSONObject();
                    json.put("cntrSizeType", qd.getCntrSizeType());
                    json.put("cntrCount",qd.getCntrCount());
                    json.put("goods",qd.getGoods());
                    array.add(json);
                }
            }
            order.setCntrMsg(array.toString());
        }

        boolean b = save(order);
        //班列发运、普通发运、水转铁、提重以及提重回空重箱子的发运到达状态只能有一个
        List<String> ddcntrnoList = new ArrayList<>();
        List<String> fycntrnoList = new ArrayList<>();
        if (!vo.getCntrList().isEmpty()){
            List<CntrInfo> cntrInfos=new ArrayList<>();
            List<CntrLog> cntrLogs=new ArrayList<>();
            String[] ZX={YwOrderTypeEnum.ZJ.getCode(),YwOrderTypeEnum.TZ.getCode(),YwOrderTypeEnum.TZHK.getCode()};
            for (YwOrderCntr ywOrderCntr : vo.getCntrList()) {
                if (vo.getFinishFlag()!=0){
                CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
                CntrLog cntrLog=new CntrLog();
                if(cntrInfo!=null){
                    cntrInfo.setRemark("提交受理");
                    if(YwOrderTypeEnum.TZ.getCode().equals(order.getOrderType()) || YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
                        cntrInfo.setCntrWorkRemarkB(DdEnum.DSL.getName());
                        cntrInfo.setCntrWorkRemark(null);
                        ddcntrnoList.add(cntrInfo.getCntrNo());
                    }else{
                        cntrInfo.setCntrWorkRemark(FyEnum.DSL.getName());
                        cntrInfo.setCntrWorkRemarkB(null);
                        fycntrnoList.add(cntrInfo.getCntrNo());
                    }
                    cntrInfo.setCompanyId(order.getCompanyId());
                    cntrInfo.setCntrSize(ywOrderCntr.getCntrSize());
                    cntrInfo.setOrderNo(order.getOrderNo());
                    cntrInfo.setStartPort(ywOrderCntr.getInitialStation());//发站
                    cntrInfo.setConsigner(ywOrderCntr.getShipper());//发货公司
                    cntrInfo.setEndPort(ywOrderCntr.getDestination());//到站
                    cntrInfo.setConsignee(ywOrderCntr.getConsignee());//收货公司
                    cntrInfo.setConsigneeLx(ywOrderCntr.getReceiveName());//收货人
                    cntrInfo.setConsigneePhone(ywOrderCntr.getReceivePhone());//收货人联系方式
                    cntrInfos.add(cntrInfo);
                    BeanUtils.copyProperties(cntrInfo,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLog.setUserName(order.getUserName());
                    cntrLogs.add(cntrLog);
                }else{
                    CntrInfo cntrInfo1=new CntrInfo();
                    cntrInfo1.setOrderNo(order.getOrderNo());
                    cntrInfo1.setCntrNo(ywOrderCntr.getCntrNo());
                    cntrInfo1.setCntrSize(ywOrderCntr.getCntrSize());
                    cntrInfo1.setStatus(1);
                    cntrInfo1.setRemark("提交受理");
                    cntrInfo1.setGoods(ywOrderCntr.getGoodsName());//货物名称
                    cntrInfo1.setEfFlag(ywOrderCntr.getEfFlag());//空重
                    if(StrUtil.isNotBlank(ywOrderCntr.getWeight())){
                        cntrInfo1.setWeightPred( Double.parseDouble(ywOrderCntr.getWeight()));//预报重量\箱货重量
                    }
                    cntrInfo1.setCompanyId(order.getCompanyId());
                    cntrInfo1.setSealNo(ywOrderCntr.getSealNo());//铅封号
                    cntrInfo1.setStartPort(ywOrderCntr.getInitialStation());//发站
                    cntrInfo1.setConsigner(ywOrderCntr.getShipper());//发货公司
                    cntrInfo1.setEndPort(ywOrderCntr.getDestination());//到站
                    cntrInfo1.setConsignee(ywOrderCntr.getConsignee());//收货公司
                    cntrInfo1.setConsigneeLx(ywOrderCntr.getReceiveName());//收货人
                    cntrInfo1.setConsigneePhone(ywOrderCntr.getReceivePhone());//收货人联系方式
                    cntrInfo1.setAccesspath("PC");//操作端
                    cntrInfo1.setUserId(vo.getUserId());//操作id
                    cntrInfo1.setUserName(vo.getUserName());//操作人名字
                    cntrInfo1.setCreatetime(LocalDateTime.now());
                    if(YwOrderTypeEnum.TZ.getCode().equals(order.getOrderType()) || YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
                        cntrInfo1.setCntrWorkRemarkB(DdEnum.DSL.getName());
                    }else{
                        cntrInfo1.setCntrWorkRemark(FyEnum.DSL.getName());
                    }
                    cntrInfos.add(cntrInfo1);
                    BeanUtils.copyProperties(cntrInfo1,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLog.setUserName(order.getUserName());
                    cntrLogs.add(cntrLog);
                }
                }

                ywOrderCntr.setOrderNo(orderNo);
                ywOrderCntr.setCompanyId(vo.getCompanyId());
                if(StringUtils.isEmpty(ywOrderCntr.getInitialStation())){
                    ywOrderCntr.setInitialStation("香炉山");
                }
            }
            if (vo.getFinishFlag()!=0){
                            cntrInfoService.saveOrUpdateBatch(cntrInfos);
            if(!ddcntrnoList.isEmpty()){
                cntrInfoService.update(null,Wrappers.<CntrInfo>lambdaUpdate()
                        .set(CntrInfo::getCntrWorkRemark,null)
                        .in(CntrInfo::getCntrNo,ddcntrnoList));
            }
            if(!fycntrnoList.isEmpty()){
                cntrInfoService.update(null,Wrappers.<CntrInfo>lambdaUpdate()
                        .set(CntrInfo::getCntrWorkRemarkB,null)
                        .in(CntrInfo::getCntrNo,fycntrnoList));
            }
            cntrLogService.saveOrUpdateBatch(cntrLogs);

            }
            ywOrderCntrService.saveBatch(vo.getCntrList());
            if(vo.getFinishFlag()==1){//提交
                //yzs提交业务 --发送消息---给市场部
                notifyService.saveYwMsg(order,url);
            }
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateOrder(YwOrderVo vo) {
        if(vo.getFinishFlag()!=null && vo.getFinishFlag()==1 && vo.getCntrList().isEmpty()){
            if(vo.getCntrQdList()==null){
                return ResultUtil.build(ResultUtilCodeEnum.YWORDER_NO_CNTR);
            }
        }
        YwOrder order = getById(vo.getId());
        order.setOrderType(vo.getOrderType());
        order.setCompanyId(vo.getCompanyId());
        order.setOrderState(vo.getOrderState());
        order.setCompanyName(vo.getCompanyName());
        order.setWorkTime(vo.getWorkTime());
        order.setUpdateUserId(vo.getUpdateUserId());
        order.setUpdateUserName(vo.getUpdateUserName());
        order.setEfcomState(vo.getEfcomState());
        order.setUpdateTime(LocalDateTime.now());
        order.setTkWorkState(vo.getTkWorkState());
        if (("TK".equals(vo.getOrderType()) || "KJ".equals(vo.getOrderType()) || "HK".equals(vo.getOrderType())) && (vo.getTkWorkState()!=null && vo.getTkWorkState()==1) ){
            JSONArray array = new JSONArray();
            if (!vo.getCntrQdList().isEmpty()){
                List<CntrQdVo> voList = vo.getCntrQdList();
                for (CntrQdVo qd : voList) {
                    JSONObject json=new JSONObject();
                    json.put("cntrSizeType", qd.getCntrSizeType());
                    json.put("cntrCount",qd.getCntrCount());
                    json.put("goods",qd.getGoods());
                    array.add(json);
                }
            }
            order.setCntrMsg(array.toString());
        }

        boolean b = updateById(order);
        //代码有bug 箱子会删除 暂不知道这段作用
//        List<YwOrderCntr> ywOrderCntrs = ywOrderCntrService.list(new QueryWrapper<YwOrderCntr>()
//                .eq("disable", 0)
//                .eq("order_no", order.getOrderNo()));
//        if (!ywOrderCntrs.isEmpty()){
//
//            List<CntrInfo> cntrInfos=new ArrayList<>();
//            for (YwOrderCntr ywOrderCntr : ywOrderCntrs) {
//                ywOrderCntr.setDisable(1);
//                CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
//                if(cntrInfo!=null){
//                    cntrInfo.setCntrWorkRemark("");
//                    cntrInfos.add(cntrInfo);
//                }
//            }
//            ywOrderCntrService.updateBatchById(ywOrderCntrs);
//            cntrInfoService.updateBatchById(cntrInfos);
//
//        }
        if (!vo.getCntrList().isEmpty() && order.getFinishFlag()==0){
            List<CntrInfo> cntrInfos=new ArrayList<>();
            List<CntrLog> cntrLogs=new ArrayList<>();
            for (YwOrderCntr ywOrderCntr : vo.getCntrList()) {
                CntrLog cntrLog=new CntrLog();
                ywOrderCntr.setOrderNo(order.getOrderNo());
                ywOrderCntr.setCompanyId(vo.getCompanyId());
                if(StringUtils.isEmpty(ywOrderCntr.getInitialStation())){
                    ywOrderCntr.setInitialStation("香炉山");
                }
                ywOrderCntr.setUpdateUserId(vo.getId());
                ywOrderCntr.setUpdateTime(LocalDateTime.now());

                CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
                if(cntrInfo!=null){
                    cntrInfo.setRemark("提交受理");
                    if("TZ".equals(order.getOrderType()) || YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
                        cntrInfo.setCntrWorkRemarkB(DdEnum.DSL.getName());
                        cntrInfo.setCntrWorkRemark(null);
                    }else{
                        cntrInfo.setCntrWorkRemark(FyEnum.DSL.getName());
                        cntrInfo.setCntrWorkRemarkB(null);
                    }
                    cntrInfo.setCompanyId(order.getCompanyId());
                    cntrInfos.add(cntrInfo);
                    BeanUtils.copyProperties(cntrInfo,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLogs.add(cntrLog);
                }else{
                    CntrInfo cntrInfo1=new CntrInfo();
                    cntrInfo1.setRemark("提交受理");
                    cntrInfo1.setCntrNo(ywOrderCntr.getCntrNo());
                    cntrInfo1.setCntrSize(ywOrderCntr.getCntrSize());

                    cntrInfo1.setStatus(1);
                    cntrInfo1.setCreatetime(LocalDateTime.now());
                    if("TZ".equals(order.getOrderType()) || YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
                        cntrInfo1.setCntrWorkRemarkB(DdEnum.DSL.getName());
                        cntrInfo1.setCntrWorkRemark(null);
                    }else{
                        cntrInfo1.setCntrWorkRemark(FyEnum.DSL.getName());
                        cntrInfo1.setCntrWorkRemarkB(null);
                    }
                    cntrInfo1.setCompanyId(order.getCompanyId());
                    cntrInfos.add(cntrInfo1);
                    BeanUtils.copyProperties(cntrInfo1,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLogs.add(cntrLog);
                }
            }
            cntrLogService.saveOrUpdateBatch(cntrLogs);
            cntrInfoService.saveOrUpdateBatch(cntrInfos);
            ywOrderCntrService.updateBatchById(vo.getCntrList());
        }

        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> deleteOrder(Integer id) {
        YwOrder ywOrder = getById(id);
        ywOrder.setDisable(1);
        List<YwOrderCntr> cntrList = ywOrderCntrService.list(Wrappers.lambdaQuery(YwOrderCntr.class)
                .eq(YwOrderCntr::getDisable, 0)
                .eq(YwOrderCntr::getOrderNo, ywOrder.getOrderNo()));
        //遍历cntrList如果有理货无法删除
        for (YwOrderCntr ywOrderCntr : cntrList){
            if(ywOrderCntr.getTallyState() ==10){
                return ResultUtil.build(ResultUtilCodeEnum.YWCNTR_IS_TALLY);
            }
        }

        if (cntrList.size() > 0) {
            if (cntrList.stream().anyMatch(s -> s.getTallyState() != 0)) {
                return ResultUtil.build(ResultUtilCodeEnum.YWCNTR_IS_TALLY);
            }
            List<CntrInfo> cntrInfos = new ArrayList<>();
            for (YwOrderCntr ywOrderCntr : cntrList) {
                ywOrderCntr.setDisable(1);
                CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
                if (cntrInfo != null) {
                    CntrInfo cntrInfo1 = deleteCntrInfo(cntrInfo);
                    cntrInfos.add(cntrInfo1);
                }
            }
            cntrInfoService.updateBatchById(cntrInfos);
            ywOrderCntrService.updateBatchById(cntrList);

            //删除车辆预约和进卡记录
            List<String> delCntrList = cntrList.stream().map(YwOrderCntr::getCntrNo).collect(Collectors.toList());//待删除箱子的集装箱号
            List<VehicleReservation> vehicleReservations = vehicleReservationMapper.selectList(new QueryWrapper<VehicleReservation>().eq("disable", 0)
                    .eq("order_no", ywOrder.getOrderNo()));

            //删除车辆预约数据
            if(vehicleReservations.size()>0){
                for (VehicleReservation vehicleReservation : vehicleReservations) {
                    vehicleReservation.setDisable(1);
                }
                vehicleReservationService.updateBatchById(vehicleReservations);
                List<Long> longList = vehicleReservations.stream().map(VehicleReservation::getId).collect(Collectors.toList());
                List<DeclareCar> declareCars = declareCarMapper.selectList(new QueryWrapper<DeclareCar>().eq("disable", 0)
                        .and(wrapper -> wrapper.in("vehicle_id", longList).or().in("vehicle_id_b", longList)));
                if(declareCars.size()>0){
                    for (DeclareCar declareCar : declareCars) {
                        if(declareCar.getVehicleId()!=null){
                            if(longList.contains(declareCar.getVehicleId())){
                                declareCar.setVehicleId(null);
                            }
                        }
                        if(declareCar.getVehicleIdB()!=null){
                            if(longList.contains(declareCar.getVehicleIdB())){
                                declareCar.setVehicleIdB(null);
                            }
                        }
                        if(declareCar.getVehicleId()==null && declareCar.getVehicleIdB() ==null){
                            declareCar.setDisable(1);
                        }
                        declareCarMapper.updateById(declareCar);
                    }
                }
            }

            //删除进卡记录
            List<CntrLog> cntrLogs = cntrLogService.getBaseMapper().selectList(new QueryWrapper<CntrLog>().eq("disable", 0)
                    .eq("order_no", ywOrder.getOrderNo()).eq("remark", "集装箱进卡").in("cntr_no", delCntrList));
            if(cntrLogs.size()>0){
                for (CntrLog cntrLog : cntrLogs) {
                    cntrLog.setDisable(1);
                }
                cntrLogService.updateBatchById(cntrLogs);
            }
        }

        boolean b = updateById(ywOrder);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    private CntrInfo deleteCntrInfo(CntrInfo cntrInfo) {
        //TODO

        CntrInfo cntrInfo1=new CntrInfo();
        BeanUtils.copyProperties(cntrInfo,cntrInfo1);
        cntrInfo1.setCntrWorkRemark(null);
        cntrInfo1.setCntrWorkRemarkB(null);
        cntrInfo1.setCntrRemark("");
        cntrInfo1.setStartPort("");
        cntrInfo1.setEndPort("");
        cntrInfo1.setSpecialWay("");
        cntrInfo1.setConsigneeLx("");
        cntrInfo1.setConsigneePhone("");
        cntrInfo1.setConsignee("");
        cntrInfo1.setConsigner("");
        cntrInfo1.setMdPort("");
        cntrInfo1.setZhPort("");
        cntrInfo1.setOrderNo("");
        cntrInfo1.setCarNo("");
        cntrInfo1.setRemark("");
        cntrInfo1.setGoods("");
        cntrInfo1.setSealNo("");
        cntrInfo1.setWeightPred(null);
        return cntrInfo1;
    }

    @Override
    public ResultUtil<T> updateCheck(YwOrderVo vo) {
//        if((vo.getFinishFlag()==null||vo.getFinishFlag()==1 )&& vo.getCntrList()==null){
//            return ResultUtil.build(ResultUtilCodeEnum.YWORDER_NO_CNTR);
//        }// 前端只发了一个id 这个用不了
        YwOrder order = getById(vo.getId());
        List<YwOrderCntr> ywOrderCntrs = cntrMapper.selectList(
                new LambdaQueryWrapper<YwOrderCntr>()
                        .eq(YwOrderCntr::getOrderNo, order.getOrderNo())
                        .eq(YwOrderCntr::getDisable, 0));
        if(!(YwOrderTypeEnum.SGJ.getCode().equals(order.getOrderType()))){
            if(ywOrderCntrs.size()==0 && StringUtils.isEmpty(order.getCntrMsg())){
                return ResultUtil.build(ResultUtilCodeEnum.YWORDER_NO_CNTR);
            }
        }
        YwOrder ywOrder = getById(vo.getId());
        ywOrder.setFinishFlag(2);
        ywOrder.setAuditTime(ywOrder.getCreateTime());
        ywOrder.setAuditEndTime(LocalDateTime.parse(ywOrder.getAuditTime().toLocalDate().plusDays(6) +" 23:59:59",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        ywOrder.setAuditUserName(vo.getAuditUserName());
        boolean b = updateById(ywOrder);
        ywOrder.setUpdateUserId(vo.getUpdateUserId());//审核人(操作人)
        List<YwOrderCntr> cntrList = ywOrderCntrService.list(Wrappers.lambdaQuery(YwOrderCntr.class)
                .eq(YwOrderCntr::getDisable, 0)
                .eq(YwOrderCntr::getOrderNo, ywOrder.getOrderNo()));
        if(cntrList.size()>0){
            List<CntrInfo> cntrInfos=new ArrayList<>();
            List<CntrLog> cntrLogs=new ArrayList<>();
            for (YwOrderCntr ywOrderCntr : cntrList) {
                CntrLog cntrLog=new CntrLog();
                CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
                if(cntrInfo!=null){
                    cntrInfo.setRemark("受理");
                    if("TZ".equals(ywOrder.getOrderType()) || "TZHK".equals(ywOrder.getOrderType()) ){
                        cntrInfo.setCntrWorkRemarkB(DdEnum.YSL.getName());
                    }else{
                        cntrInfo.setCntrWorkRemark(FyEnum.YSL.getName());
                    }
                    cntrInfos.add(cntrInfo);
                    BeanUtils.copyProperties(cntrInfo,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLog.setUserName(vo.getAuditUserName());
                    cntrLogs.add(cntrLog);
                }
            }
            cntrInfoService.updateBatchById(cntrInfos);
            cntrLogService.saveOrUpdateBatch(cntrLogs);
            ywOrderCntrService.updateBatchById(cntrList);
            if (b){
                //1.cms市场部受理后--消息提醒yzs客户company
                notifyService.saveMsgToYzsCom(ywOrder);
                //2.cms市场部受理后--消息提醒cms运营部organization
                notifyService.saveMsgToCmsYYB(ywOrder);
            }
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public List<YwOrderVo> getYwOrderVoJson(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> iPage = baseMapper.getYwOrderVoJson1(page,vo);
//        IPage<YwOrderVo> iPage = baseMapper.getYwOrderVoJson(page,vo);

        List<YwOrderVo> records = new ArrayList<>(iPage.getRecords());

        //当前车队 被授权的 业务号
        List<String> orderNos = authMapper.selectByAuth(vo.getCompanyId(), vo.getOrderType());
        for (String orderNo : orderNos) {
            YwOrderVo vo1 = baseMapper.getByOrderNo(orderNo);
            if(vo1!=null){
                records.add(vo1);
            }
        }

        Map<String, String> orderTypeMap = YwOrderTypeEnum.stream()
                .collect(Collectors.toMap(YwOrderTypeEnum::getCode, YwOrderTypeEnum::getName));

        for (YwOrderVo record : records) {
            String orderType = record.getOrderType();
            // 检查Map中是否有对应的orderType
            if (orderTypeMap.containsKey(orderType)) {
                record.setOrderTypeName(orderTypeMap.get(orderType));
            }
            record.setText(record.getOrderTypeName()+"/"+record.getOrderNo()+"/"+record.getCompanyName()+"/");
            if(record.getSmallNum()!=null){
                record.setText(record.getText()+"小箱"+record.getSmallNum()+"个/");
            }
            if(record.getBigNum()!=null){
                record.setText(record.getText()+"大箱"+record.getBigNum()+"个");
            }
        }
        return records;
    }

    //提空重进
    @Override
    public ResultUtil<T> addTkzjOrder(HttpServletRequest request, YwOrderVo vo) {
        YwOrder order = new YwOrder();
        order.setOrderType(vo.getOrderType());
        order.setCompanyId(vo.getCompanyId());
        order.setOrderState(vo.getOrderState());
        order.setCompanyName(vo.getCompanyName());
        order.setWorkTime(vo.getWorkTime());
        String orderNo = "E" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        order.setOrderNo(orderNo);
        order.setUserId(vo.getUserId());//创建人
        boolean b = save(order);
        List<YwOrderCntr> ywOrderCntrs=new ArrayList<>();
        if (!vo.getCntrList().isEmpty()){
            for (YwOrderCntr cntr : vo.getCntrList()) {
                cntr.setInitialStation(vo.getInitialStation());
                cntr.setShipper(vo.getShipper());
                cntr.setEfFlag("E");
                cntr.setDestination(vo.getDestination());
                cntr.setConsignee(vo.getConsignee());
                cntr.setCreateTime(LocalDateTime.now());
                cntr.setOrderNo(order.getOrderNo());
                cntr.setCompanyId(vo.getCompanyId());
                for (int i = 0; i < cntr.getCntrNum(); i++) {
                    ywOrderCntrs.add(cntr);
                }
            }
            if(!ywOrderCntrs.isEmpty()){
                ywOrderCntrService.saveBatch(ywOrderCntrs);
            }
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateTkzjOrder(YwOrderVo vo) {
        YwOrder order = getById(vo.getId());
        order.setOrderType(vo.getOrderType());
        order.setCompanyId(vo.getCompanyId());
        order.setCompanyName(vo.getCompanyName());
        order.setWorkTime(vo.getWorkTime());
        order.setUpdateUserId(vo.getUpdateUserId());
        order.setUpdateUserName(vo.getUpdateUserName());
        order.setUpdateTime(LocalDateTime.now());
        boolean b = updateById(order);
        List<YwOrderCntr> ywOrderCntrList = ywOrderCntrService.list(new QueryWrapper<YwOrderCntr>()
                .eq("disable", 0)
                .eq("order_no", order.getOrderNo()));
        if (!ywOrderCntrList.isEmpty()){
            ywOrderCntrService.removeByIds(ywOrderCntrList.stream().map(YwOrderCntr::getId).collect(Collectors.toList()));
        }
        List<YwOrderCntr> ywOrderCntrs=new ArrayList<>();
        if (!vo.getCntrList().isEmpty()){
            for (YwOrderCntr cntr : vo.getCntrList()) {
                cntr.setInitialStation(vo.getInitialStation());
                cntr.setShipper(vo.getShipper());
                cntr.setDestination(vo.getDestination());
                cntr.setConsignee(vo.getConsignee());
                cntr.setCreateTime(LocalDateTime.now());
                cntr.setOrderNo(order.getOrderNo());
                cntr.setCompanyId(vo.getCompanyId());
                for (int i = 0; i < cntr.getCntrNum(); i++) {
                    ywOrderCntrs.add(cntr);
                }
            }
            if(!ywOrderCntrs.isEmpty()){
                ywOrderCntrService.saveBatch(ywOrderCntrs);
            }
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> addTzOrder(YwOrderVo vo) {
        YwOrder order = new YwOrder();
        order.setOrderType(vo.getOrderType());
        order.setCompanyId(vo.getCompanyId());
        order.setCompanyName(vo.getCompanyName());
        order.setOrderState(vo.getOrderState());
        order.setFinishFlag(vo.getFinishFlag());
        order.setWorkTime(vo.getWorkTime());
        order.setCreateTime(vo.getCreateTime());
        order.setUserId(vo.getUserId());
        order.setUserName(vo.getUserName());
        String orderNo  = "K" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        order.setOrderNo(orderNo);
        boolean b = save(order);
        if (!vo.getCntrList().isEmpty()){
            for (YwOrderCntr ywOrderCntr : vo.getCntrList()) {
                ywOrderCntr.setOrderNo(orderNo);
                ywOrderCntr.setEfFlag("F");
                ywOrderCntr.setCompanyId(vo.getCompanyId());
                if(StringUtils.isEmpty(ywOrderCntr.getDestination())){
                    ywOrderCntr.setDestination("香炉山");
                }
            }
            ywOrderCntrService.saveBatch(vo.getCntrList());
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateTzOrder(YwOrderVo vo) {
        YwOrder order = getById(vo.getId());
        order.setOrderType(vo.getOrderType());
        order.setCompanyId(vo.getCompanyId());
        order.setCompanyName(vo.getCompanyName());
        order.setWorkTime(vo.getWorkTime());
        order.setUpdateUserId(vo.getUpdateUserId());
        order.setUpdateUserName(vo.getUpdateUserName());
        order.setUpdateTime(LocalDateTime.now());
        boolean b = updateById(order);
        List<YwOrderCntr> ywOrderCntrs = ywOrderCntrService.list(new QueryWrapper<YwOrderCntr>()
                .eq("disable", 0)
                .eq("order_no", order.getOrderNo()));
        if (!ywOrderCntrs.isEmpty()){
            ywOrderCntrs.forEach(s->s.setDisable(1));
            ywOrderCntrService.updateBatchById(ywOrderCntrs);
        }
        if (!vo.getCntrList().isEmpty()){
            vo.getCntrList().forEach(s->s.setCreateTime(LocalDateTime.now())
                    .setUpdateUserId(vo.getId())
                    .setUpdateTime(LocalDateTime.now())
                    .setOrderNo(order.getOrderNo())
                    .setCompanyId(order.getCompanyId()));
            ywOrderCntrService.saveBatch(vo.getCntrList());
        }

        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> addSgjOrder(YwOrderVo vo,String url) {
        YwOrder order = new YwOrder();
        BeanUtils.copyProperties(vo,order);
        order.setCreateTime(LocalDateTime.now());
        String orderNo = "SGJ" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        order.setOrderNo(orderNo);
        boolean b = save(order);
        if (b){
            if (!vo.getShipList().isEmpty()){
                vo.getShipList().forEach(s->s.setCreateTime(LocalDateTime.now())
                        .setUserId(vo.getId())
                        .setOrderNo(order.getOrderNo()));
                ywOrderShipService.saveBatch(vo.getShipList());
            }
            if(vo.getFinishFlag()==1){//提交
                //yzs提交业务 --发送消息---给市场部
                notifyService.saveYwMsg(order,url);
            }
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public List<YwOrderVo> getAllSgjList(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> iPage = baseMapper.getAllSgjList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> updateSgjOrder(YwOrderVo vo) {
        YwOrder order = getById(vo.getId());
        BeanUtils.copyProperties(vo,order);
        boolean b = updateById(order);
        if (b){
            if (!vo.getShipList().isEmpty()){
                //先删除所有
                List<YwOrderShip> shipList = ywOrderShipService.list(Wrappers.lambdaQuery(YwOrderShip.class)
                        .eq(YwOrderShip::getDisable, 0)
                        .eq(YwOrderShip::getOrderNo, order.getOrderNo()));
                if(shipList.size()>0){
                    for (YwOrderShip ywOrderShip : shipList) {
                        ywOrderShip.setDisable(1);
                    }
                    ywOrderShipService.updateBatchById(shipList);
                }
                vo.getShipList().forEach(s -> s.setId(null).setOrderNo(order.getOrderNo()));
                ywOrderShipService.saveBatch(vo.getShipList());
            }
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> deleteSgjOrder(Long id) {
        YwOrder order = getById(id);
        order.setDisable(1);
        boolean b = updateById(order);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public List<YwOrderVo> getYwOrderSgjList(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> iPage = baseMapper.getOrderPage(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> AddSgjCntrAndCarMsg(YwOrderVo vo) {
        SysUser user = userMapper.selectById(vo.getUserId());
        List<CntrInfo> cntrSgjList = vo.getCntrSgjList();
        List<CarInfo> carList = vo.getCarList();
        for (CntrInfo cntr : cntrSgjList) {
            YwOrderCntr orderCntr = new YwOrderCntr();
            BeanUtils.copyProperties(cntr,orderCntr);
            orderCntr.setUserId(user.getId());
            orderCntr.setCreateTime(LocalDateTime.now());
            orderCntr.setOrderNo(vo.getOrderNo());
            cntrMapper.insert(orderCntr);
        }
        for (CarInfo car : carList) {
            YwOrderCar orderCar = new YwOrderCar();
            orderCar.setOrderNo(vo.getOrderNo());
            orderCar.setTruckNo(car.getCarNo());//车牌号
            orderCar.setCreateTime(LocalDateTime.now());
            orderCar.setUserId(user.getId());
            carMapper.insert(orderCar);
        }
        return ResultUtil.ok();
    }

    @Override
    public List<YwOrderVo> getYwOrderListByCarNo(Page<YwOrderVo> page,YwOrderVo vo) {
        List<String> orderList=new ArrayList<>();
        List<VehicleReservation> vehicleReservations = vehicleReservationMapper.selectList(new QueryWrapper<VehicleReservation>().eq("car_no", vo.getCarNo())
                .eq("disable", 0).eq("end_state", 0));
        if(vehicleReservations.size()>0){
            orderList.add(vehicleReservations.get(0).getOrderNo());
        }
        List<YwOrderCar> ywOrderCars = ywOrderCarMapper.getYwOrderCarList(vo);
        if(ywOrderCars.size()>0){
            orderList.add(ywOrderCars.get(0).getOrderNo());
        }
        Map<String, String> orderTypeMap = YwOrderTypeEnum.stream()
                .collect(Collectors.toMap(YwOrderTypeEnum::getCode, YwOrderTypeEnum::getName));
        IPage<YwOrderVo> iPage=new Page<>();

        if(orderList.size()>0){
            vo.setOrderList(orderList);
            iPage = baseMapper.getYwOrderVoJson(page,vo);
            for (YwOrderVo record : iPage.getRecords()) {
                String orderType = record.getOrderType();
                // 检查Map中是否有对应的orderType
                if (orderTypeMap.containsKey(orderType)) {
                    record.setOrderTypeName(orderTypeMap.get(orderType));
                }
                record.setText(record.getOrderTypeName()+"/"+record.getOrderNo()+"/"+record.getCompanyName()+"/");
                if(record.getSmallNum()!=null){
                    record.setText(record.getText()+"小箱"+record.getSmallNum()+"个/");
                }
                if(record.getBigNum()!=null){
                    record.setText(record.getText()+"大箱"+record.getBigNum()+"个");
                }
            }
        }
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> updateSgjPlan(YwOrderVo vo) {
        List<CntrInfo> cntrSgjList = vo.getCntrSgjList();
        List<CarInfo> carList = vo.getCarList();
        if(carList.size()>0){
            List<String> list=new ArrayList<>();
            for (CarInfo info : carList) {
                list.add(info.getCarNo());
            }
            List<YwOrderCar> ywOrderCars = carMapper.selectList(new QueryWrapper<YwOrderCar>().eq("disable", 0)
                    .ne("order_no", vo.getOrderNo()).in("truck_no", list));
            if(ywOrderCars.size()>0){
                return ResultUtil.build(400,"车牌号"+ywOrderCars.get(0).getTruckNo()+"已安排!");
            }
        }

        //先清除yw_order_car表信息
        LambdaUpdateWrapper<YwOrderCar> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.eq(YwOrderCar::getOrderNo,vo.getOrderNo())
                .set(YwOrderCar::getDisable,1);
        ywOrderCarService.update(wrapper1);

        //再新增
        SysUser user = userMapper.selectById(vo.getUserId());

        for (CarInfo car : carList) {
            YwOrderCar orderCar = new YwOrderCar();
            orderCar.setOrderNo(vo.getOrderNo());
            orderCar.setTruckNo(car.getCarNo());//车牌号
            orderCar.setCreateTime(LocalDateTime.now());
            orderCar.setUserId(user.getId());
            carMapper.insert(orderCar);
        }
        return ResultUtil.ok();


    }

    @Override
    public List<YwOrderCntr> getSgjCntrMsg(YwOrderCntr cntr) {
        return cntrMapper.getSgjCntrMsg(cntr);
    }

    @Override
    public List<YwOrderCarVo> getSgjCarMsg(YwOrderCarVo car) {
        return carMapper.getSgjCarMsg(car);
    }

    @Override
    public ResultUtil<T> SgjIssued(YwOrderVo vo) {
        YwOrder order = getById(vo.getId());
        LambdaQueryWrapper<YwOrderCntr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YwOrderCntr::getOrderNo,vo.getOrderNo());
        Integer cntrNum = cntrMapper.selectCount(wrapper);
        LambdaQueryWrapper<YwOrderCar> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(YwOrderCar::getOrderNo,vo.getOrderNo());

        Integer carNum = carMapper.selectCount(wrapper1);
        if (cntrNum==0){
            return ResultUtil.build( ResultUtilCodeEnum.SGJ_CNTR_IS_NULL);
        }
        if (carNum==0){
            return ResultUtil.build( ResultUtilCodeEnum.SGJ_CAR_IS_NULL);
        }

        order.setFinishFlag(3);
        boolean b = updateById(order);
        if (b){
            List<YwOrderCntr> cntrList = ywOrderCntrService.list(Wrappers.lambdaQuery(YwOrderCntr.class)
                    .eq(YwOrderCntr::getDisable, 0)
                    .eq(YwOrderCntr::getOrderNo, order.getOrderNo()));
            if(cntrList.size()>0){
                List<CntrInfo> cntrInfos=new ArrayList<>();
                List<CntrLog> cntrLogs=new ArrayList<>();
                for (YwOrderCntr ywOrderCntr : cntrList) {
                    CntrLog cntrLog=new CntrLog();
                    CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
                    if(cntrInfo!=null){
                        cntrInfo.setRemark("受理");
                        cntrInfo.setCntrWorkRemark(FyEnum.YSL.getName());
                        cntrInfos.add(cntrInfo);
                        BeanUtils.copyProperties(cntrInfo,cntrLog);
                        cntrLog.setCreatetime(LocalDateTime.now());
                        cntrLogs.add(cntrLog);
                    }
                }
                cntrInfoService.updateBatchById(cntrInfos);
                cntrLogService.saveOrUpdateBatch(cntrLogs);
            }
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> submitOrder(YwOrderVo vo) {
        YwOrder order = getById(vo.getId());
        List<YwOrderCntr> ywOrderCntrs = cntrMapper.selectList(
                new LambdaQueryWrapper<YwOrderCntr>()
                        .eq(YwOrderCntr::getOrderNo, order.getOrderNo())
                        .eq(YwOrderCntr::getDisable, 0));
        if(!(YwOrderTypeEnum.SGJ.getCode().equals(order.getOrderType()) || ("TZ".equals(order.getOrderType())) || (YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType()))) ){
            if(ywOrderCntrs.size()==0){
                return ResultUtil.build(ResultUtilCodeEnum.YWORDER_NO_CNTR);
            }
        }
        //箱照片 水运单校验 白名单可通过
        CompanyInfo companyInfo = companyInfoMapper.selectById(order.getCompanyId());
        if(companyInfo.getIsWhite()==0){
            List<CntrImgFile> cntrImgFiles = cntrImgFileMapper.selectList(new QueryWrapper<CntrImgFile>().eq("disable", 0).eq("order_no", order.getOrderNo()));
            List<YwOrderFile> ywOrderFiles = ywOrderFileMapper.selectList(new QueryWrapper<YwOrderFile>().eq("disable", 0).eq("order_no", order.getOrderNo()));
            if(cntrImgFiles.size()==0 && !(("SGJ".equals(order.getOrderType())) || ("TZ".equals(order.getOrderType())) || (YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())))){
                return ResultUtil.build( ResultUtilCodeEnum.SGJ_IMG_IS_NULL);
            }
            if(ywOrderFiles.size()==0 && (order.getOrderState() == 1 || order.getOrderState() == 2)){
                return ResultUtil.build( ResultUtilCodeEnum.SGJ_YUNYUN_IS_NULL);
            }
            if(vo.getFinishFlag()!=null && vo.getFinishFlag()==1 && vo.getCntrList().isEmpty()){
                return ResultUtil.build(ResultUtilCodeEnum.YWORDER_NO_CNTR);
            }
        }
        if(ywOrderCntrs!=null){
            List<CntrInfo> cntrInfos=new ArrayList<>();
            List<CntrLog> cntrLogs=new ArrayList<>();
            for (YwOrderCntr ywOrderCntr : ywOrderCntrs) {
                CntrInfo cntrInfo = cntrInfoMapper.getCntrInfoById(ywOrderCntr.getCntrNo());
                CntrLog cntrLog=new CntrLog();
                if(cntrInfo!=null){
                    cntrInfo.setRemark("提交受理");
                    if(YwOrderTypeEnum.TZ.getCode().equals(order.getOrderType()) || YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
                        cntrInfo.setCntrWorkRemarkB(DdEnum.DSL.getName());
                        cntrInfo.setCntrWorkRemark(null);
                    }else{
                        cntrInfo.setCntrWorkRemark(FyEnum.DSL.getName());
                        cntrInfo.setCntrWorkRemarkB(null);
                    }
                    cntrInfo.setCompanyId(order.getCompanyId());
                    cntrInfo.setOrderNo(order.getOrderNo());
                    cntrInfos.add(cntrInfo);
                    BeanUtils.copyProperties(cntrInfo,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLogs.add(cntrLog);
                }else{
                    CntrInfo cntrInfo1=new CntrInfo();
                    cntrInfo1.setOrderNo(order.getOrderNo());
                    cntrInfo1.setCntrNo(ywOrderCntr.getCntrNo());
                    cntrInfo1.setCntrSize(ywOrderCntr.getCntrSize());
                    cntrInfo1.setStatus(1);
                    cntrInfo1.setRemark("提交受理");
                    cntrInfo1.setGoods(ywOrderCntr.getGoodsName());//货物名称
                    cntrInfo1.setEfFlag(ywOrderCntr.getEfFlag());//空重
                    if(StrUtil.isNotBlank(ywOrderCntr.getWeight())){
                        cntrInfo1.setWeightPred( Double.parseDouble(ywOrderCntr.getWeight()));//预报重量\箱货重量
                    }
                    cntrInfo1.setCompanyId(order.getCompanyId());
                    cntrInfo1.setSealNo(ywOrderCntr.getSealNo());//铅封号
                    cntrInfo1.setStartPort(ywOrderCntr.getInitialStation());//发站
                    cntrInfo1.setConsigner(ywOrderCntr.getShipper());//发货公司
                    cntrInfo1.setEndPort(ywOrderCntr.getDestination());//到站
                    cntrInfo1.setConsignee(ywOrderCntr.getConsignee());//收货公司
                    cntrInfo1.setConsigneeLx(ywOrderCntr.getReceiveName());//收货人
                    cntrInfo1.setConsigneePhone(ywOrderCntr.getReceivePhone());//收货人联系方式
                    cntrInfo1.setAccesspath("PC");//操作端
                    cntrInfo1.setUserId(vo.getUserId());//操作id
                    cntrInfo1.setUserName(vo.getUserName());//操作人名字
                    cntrInfo1.setCreatetime(LocalDateTime.now());
                    if(YwOrderTypeEnum.TZ.getCode().equals(order.getOrderType()) || YwOrderTypeEnum.TZHK.getCode().equals(order.getOrderType())){
                        cntrInfo1.setCntrWorkRemarkB(DdEnum.DSL.getName());
                    }else{
                        cntrInfo1.setCntrWorkRemark(FyEnum.DSL.getName());
                    }
                    cntrInfos.add(cntrInfo1);
                    BeanUtils.copyProperties(cntrInfo1,cntrLog);
                    cntrLog.setCreatetime(LocalDateTime.now());
                    cntrLogs.add(cntrLog);
                }
            }
            cntrInfoService.saveOrUpdateBatch(cntrInfos);
            cntrLogService.saveOrUpdateBatch(cntrLogs);
        }

        order.setFinishFlag(1);
        order.setUpdateUserId(vo.getUpdateUserId());
        order.setUpdateUserName(vo.getUpdateUserName());
        order.setUpdateTime(LocalDateTime.now());
        boolean b = updateById(order);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<List<TrainPlanDetailVo>> importYwOrderFile(YwOrderVo vo, String upfolder, String accessPath) {
        YwOrder ywOrder = baseMapper.selectById(vo.getId());
        //上传文件
        saveFiles(ywOrder,vo.getFile(),upfolder,accessPath);
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil<List<TrainPlanDetailVo>> importYwOrderBillNoFile(YwOrderVo vo, String upfolder, String accessPath) {
        try {
            YwOrder ywOrder = baseMapper.selectById(vo.getId());
            List<YwOrderCntr> ywOrderCntrs = cntrMapper.selectList(
                    new LambdaQueryWrapper<YwOrderCntr>()
                            .eq(YwOrderCntr::getOrderNo, ywOrder.getOrderNo())
                            .eq(YwOrderCntr::getDisable, 0));
            if(vo.getFile()!=null){
                //识别水运单号和箱号，箱号保存图片信息
                List<CrfNoVo>  crfNoVos =  RecognizePdf.AliCloudAnalyzePDF(vo.getFile(),vo.getFile().getOriginalFilename());
                if(!crfNoVos.isEmpty()){
                    for (CrfNoVo crfNoVo : crfNoVos) {
                        crfNoVo.getCntrList().forEach(s -> {
                            for (YwOrderCntr ywOrderCntr : ywOrderCntrs) {
                                if(s.equals(ywOrderCntr.getCntrNo())){
                                    ywOrderCntr.setBillNo(crfNoVo.getRfbnum());
                                    ywOrderCntr.setBillNoImgurl(crfNoVo.getSubPdfdir());
                                    break;
                                }
                            }
                        });
                    }
                }else{
                    return ResultUtil.fail();
                }
                ywOrderCntrService.updateBatchById(ywOrderCntrs);
                //上传文件
                saveFiles(ywOrder,vo.getFile(),upfolder,accessPath);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResultUtil.fail();
        }
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil<T> deleteYwOrderFile(Integer id) {
        YwOrderFile ywOrderFile = ywOrderFileMapper.selectById(id);
        int i=0;
        if(ywOrderFile!=null){
            ywOrderFile.setDisable(1);
            i = ywOrderFileMapper.updateById(ywOrderFile);
        }
        return i>0 ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateFinish(YwOrderVo vo) {
        YwOrder ywOrder = getById(vo.getId());
        ywOrder.setFinishFlag(10);
        ywOrder.setFinishTime(LocalDateTime.now());
        ywOrder.setFinishUserName(vo.getUserName());
        boolean b = updateById(ywOrder);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> addCheckSgjOrder(YwOrderVo vo) {
        YwOrder order = new YwOrder();
        BeanUtils.copyProperties(vo,order);
        order.setFinishFlag(2);
        order.setAuditTime(LocalDateTime.now());
        order.setAuditUserName(vo.getUserName());
        order.setCreateTime(LocalDateTime.now());
        String orderNo = "SGJ" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd")) + tbSequenceService.hcseq_next_dayvalSuffix(3, "orderid");
        order.setOrderNo(orderNo);
        boolean b = save(order);
        if (b){
            if (!vo.getShipList().isEmpty()){
                vo.getShipList().forEach(s->s.setCreateTime(LocalDateTime.now())
                        .setUserId(vo.getId())
                        .setOrderNo(order.getOrderNo()));
                ywOrderShipService.saveBatch(vo.getShipList());
            }
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public YwOrderVo getByOrderNo(String orderNo) {
        return baseMapper.getByOrderNo(orderNo);
    }

    @Override
    public void autoFinishYworder() {
        List<YwOrder> ywOrders = baseMapper.selectList(new QueryWrapper<YwOrder>().eq("disable", 0)
                .eq("auto_finish", 0).isNotNull("audit_end_time").le("audit_end_time", LocalDateTime.now())) ;
        if(ywOrders.size()>0){
            for (YwOrder ywOrder : ywOrders) {
                ywOrder.setAutoFinish(1);
            }
            updateBatchById(ywOrders);
            //取消所有车辆预约信息
            List<VehicleReservation> vehicleReservations = vehicleReservationMapper.selectList(new QueryWrapper<VehicleReservation>().eq("disable", 0).in("order_no", ywOrders.stream().map(YwOrder::getOrderNo).collect(Collectors.toList())));
            if(vehicleReservations.size()>0){
                for (VehicleReservation vehicleReservation : vehicleReservations) {
                    vehicleReservation.setDisable(1);
                }
                vehicleReservationService.updateBatchById(vehicleReservations);
            }
        }

    }

    @Override
    public List<YwOrderVo> getYwOrderNoByType(YwOrderVo vo) {
        //委托给当前客户的业务号
        List<String> orderNoAuth = authMapper.selectByAuth(vo.getCompanyId(),vo.getOrderType());
        //自己公司下的委托
//        LambdaQueryWrapper<YwOrder> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(YwOrder::getOrderType,vo.getOrderType())
//                .eq(YwOrder::getCompanyId,vo.getCompanyId())
//                .eq(YwOrder::getDisable,0);
//        List<YwOrder> list = baseMapper.selectList(wrapper);

        List<YwOrderVo> list1 = baseMapper.selectYwList(vo);

        List<YwOrderVo> rel = new ArrayList<>();
        rel.addAll(list1);
        if(orderNoAuth.size()>0){
            for (String orderNo : orderNoAuth) {
                YwOrderVo order = baseMapper.getYwOrderByOrderNo(orderNo);
                if(order!=null){
                    rel.add(order);
                }
            }
        }
        return rel;
    }

    @Override
    public List<YwOrderVo> getPowerOrderList(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> iPage = baseMapper.getPowerOrderList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<YwOrderVo> getCzPowerOrderList(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> iPage = baseMapper.getCzPowerOrderList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> addPowerCar(YwOrderVo vo) {
        List<YwOrderCar> ywOrderCars=new ArrayList<>();
        boolean b=true;
        if(vo.getCarList()!=null && vo.getCarList().size()>0){
            List<YwOrderCar> oldCntrList = carMapper.selectList(new QueryWrapper<YwOrderCar>().eq("disable", 0).eq("order_no", vo.getOrderNo())
                    .eq("company_id",vo.getCompanyId()));
            if(oldCntrList.size()>0){
                List<YwOrderCar> delList = oldCntrList.stream().filter(s -> !(vo.getCarList().stream().map(CarInfo::getCarNo).collect(Collectors.toList()).contains(s.getTruckNo()))
                        && StringUtils.isNotEmpty(s.getCompanyName()) && s.getCompanyName().equals(vo.getCompanyName())).collect(Collectors.toList());
                if(delList.size()>0){
                    for (YwOrderCar ywOrderCar : delList) {
                        ywOrderCar.setDisable(1);
                    }
                    b=ywOrderCarService.updateBatchById(delList);
                }
            }

            for (CarInfo car : vo.getCarList()) {
                if(!oldCntrList.stream().anyMatch(item -> car.getCarNo().equals(item.getTruckNo()))){
                    YwOrderCar orderCar = new YwOrderCar();
                    orderCar.setOrderNo(vo.getOrderNo());
                    orderCar.setTruckNo(car.getCarNo());//车牌号
                    orderCar.setCreateTime(LocalDateTime.now());
                    orderCar.setUserId(vo.getId());
                    orderCar.setCompanyId(vo.getCompanyId());
                    orderCar.setCompanyName(vo.getCompanyName());
                    ywOrderCars.add(orderCar);
                }
            }
        }else{
            List<YwOrderCar> oldCntrList = carMapper.selectList(new QueryWrapper<YwOrderCar>().eq("disable", 0).eq("order_no", vo.getOrderNo())
                    .eq("company_id",vo.getCompanyId()));
            if(oldCntrList.size()>0){
                for (YwOrderCar ywOrderCar : oldCntrList) {
                    ywOrderCar.setDisable(1);
                }
                b=ywOrderCarService.updateBatchById(oldCntrList);
            }
        }
        if(ywOrderCars.size()>0){
            b=ywOrderCarService.saveBatch(ywOrderCars);
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> addCzPowerCar(YwOrderVo vo) {
        List<YwOrderCar> ywOrderCars=new ArrayList<>();
        boolean b=true;
        SysAuth sysAuth = authMapper.selectOne(new QueryWrapper<SysAuth>().eq("order_no", vo.getOrderNo()));
        if(sysAuth!=null){
            CompanyInfo companyInfo = companyInfoMapper.selectById(sysAuth.getSlaveComId());
            if(companyInfo!=null){
                vo.setCompanyId(companyInfo.getId());
                vo.setCompanyName(companyInfo.getName());
            }
        }else{
            CompanyInfo companyInfo = companyInfoMapper.selectById(vo.getCompanyId());
            if(companyInfo!=null){
                vo.setCompanyId(companyInfo.getId());
                vo.setCompanyName(companyInfo.getName());
            }
        }
        if(vo.getCarList()!=null && vo.getCarList().size()>0){
            List<YwOrderCar> oldCntrList = carMapper.selectList(new QueryWrapper<YwOrderCar>().eq("disable", 0).eq("order_no", vo.getOrderNo())
                    .eq("company_id",vo.getCompanyId()));
            if(oldCntrList.size()>0){
                List<YwOrderCar> delList = oldCntrList.stream().filter(s -> !(vo.getCarList().stream().map(CarInfo::getCarNo).collect(Collectors.toList()).contains(s.getTruckNo()))
                        && StringUtils.isNotEmpty(s.getCompanyName()) && s.getCompanyName().equals(vo.getCompanyName())).collect(Collectors.toList());
                if(delList.size()>0){
                    for (YwOrderCar ywOrderCar : delList) {
                        ywOrderCar.setDisable(1);
                    }
                    b=ywOrderCarService.updateBatchById(delList);
                }
            }

            for (CarInfo car : vo.getCarList()) {
                if(!oldCntrList.stream().anyMatch(item -> car.getCarNo().equals(item.getTruckNo()))){
                    YwOrderCar orderCar = new YwOrderCar();
                    orderCar.setOrderNo(vo.getOrderNo());
                    orderCar.setTruckNo(car.getCarNo());//车牌号
                    orderCar.setCreateTime(LocalDateTime.now());
                    orderCar.setUserId(vo.getId());
                    orderCar.setAuditState(1);
                    orderCar.setCompanyId(vo.getCompanyId());
                    orderCar.setCompanyName(vo.getCompanyName());
                    ywOrderCars.add(orderCar);
                }else{
                    YwOrderCar ywOrderCar = oldCntrList.stream().filter(item -> car.getCarNo().equals(item.getTruckNo())).findFirst().get();
                    ywOrderCar.setAuditState(1);
                    ywOrderCars.add(ywOrderCar);
                }
            }
        }else{
            List<YwOrderCar> oldCntrList = carMapper.selectList(new QueryWrapper<YwOrderCar>().eq("disable", 0).eq("order_no", vo.getOrderNo())
                    .eq("company_id",vo.getCompanyId()));
            if(oldCntrList.size()>0){
                for (YwOrderCar ywOrderCar : oldCntrList) {
                    ywOrderCar.setDisable(1);
                }
                b=ywOrderCarService.updateBatchById(oldCntrList);
            }
        }
        if(ywOrderCars.size()>0){
            b=ywOrderCarService.saveOrUpdateBatch(ywOrderCars);
        }
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public List<YwOrderCarVo> getPowerCarList(Page<YwOrderCarVo> page, YwOrderVo vo) {
        IPage<YwOrderCarVo> iPage = carMapper.getPowerCarList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> updateYwOrderArea(YwOrderVo vo) {
        YwOrder ywOrder = baseMapper.selectById(vo.getId());
        ywOrder.setArea(vo.getArea());
        ywOrder.setUpdateUserId(vo.getUserId());
        ywOrder.setUpdateUserName(vo.getUpdateUserName());
        ywOrder.setUpdateTime(vo.getUpdateTime());
        boolean b = updateById(ywOrder);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public List<YwOrderVo> getYwOrderList(Page<YwOrderVo> page, YwOrderVo vo) {
        IPage<YwOrderVo> iPage = baseMapper.getYwOrderList(page,vo);
        return iPage.getRecords();
    }

    public void saveFiles(YwOrder ywOrder,MultipartFile files, String upfolder, String accessPath) {
        //设置日期格式
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //当地日期转换
        String dayFormat = LocalDate.now().format(formatters);
        //创建新文件：通过路径和时间
        File folder = new File(upfolder + File.separator + dayFormat);
        //文件是否存在，不存在进行创建。
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //获取文件名
        String fileName = files.getOriginalFilename();
        //设置路径
        String path = folder + File.separator;
        File file = getFileByName(1, path, fileName);
        try {
            // 上传文件到服务器
            files.transferTo(file);
            YwOrderFile ywOrderFile = new YwOrderFile();
            ywOrderFile.setOrderNo(ywOrder.getOrderNo()).setFileSubfolder(accessPath.replaceAll("\\*", "") + dayFormat + "/")
                    .setFileName(fileName).setCreateTime(LocalDateTime.now());
            ywOrderFileMapper.insert(ywOrderFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File getFileByName(int count, String path, String fileName) {
        File file = new File(path + fileName);
        if (file.exists()) {
            // 文件名已存在
            String prefix = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")";
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            file = getFileByName(count + 1, path, prefix + suffixName);
        }
        return file;
    }
}
